import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 组合总数 {
    public List<Integer> path;
    public int sum;
    public List<List<Integer>> ans;
    public int n;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        path = new ArrayList<>();
        ans = new ArrayList<>();
        sum = 0;
        n = candidates.length;
        Arrays.sort(candidates);
        // 画出决策树进行递归
        dfs(candidates,target,0);
        return ans;
    }

    private void dfs(int[] candidates, int target, int pos) {
        if (sum == target) {
            ans.add(new ArrayList<>(path));
            return;
        }
        for (int i = pos; i < n; i++) {
            if (sum < target) {
                path.add(candidates[i]);
                sum += candidates[i];
                dfs(candidates,target,i);
                sum -= candidates[i];
                path.remove(path.size() - 1);
            } else {
                break;
            }
        }
    }
}
